<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive, onMounted, h } from 'vue'
import { Search } from '@/components/Search'
import { Table, TableColumn } from '@/components/Table'
import { FormSchema } from '@/components/Form'
import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ChatSidebarPanel } from '@/components/IntelligentChat'
import { ElMessage, ElUpload, ElButton, ElDialog, ElIcon } from 'element-plus'
import { Icon } from '@/components/Icon'
import * as XLSX from 'xlsx'
import { IntelligentChat } from '@/components/IntelligentChat'
import { custClsOptions, ecCategOptions, deregAttrTypeOptions } from '@/dicts'
import { DIFY_API_V1_URL, DIFY_API_KEY, DIFY_API_KEY_changjing1 } from '@/constants/dify'
import { DifyConfig } from '@/api/dify'
import { useRouter } from 'vue-router'
import { getArchiveVerification } from '@/api/electricityAbnormal'
import { getAbnormalOrderStatsZg } from '@/api/electricityAbnormal'

import type { ComponentPublicInstance } from 'vue'
interface ChatSidebarInstance extends ComponentPublicInstance {
  openDrawer: () => void
  closeDrawer: () => void
}

const { t } = useI18n()

// 搜索相关
const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, getFormData } = searchMethods

// 多选相关数据
const selectedRows = ref<any[]>([])

// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  console.log('selection', selection)
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 搜索表单配置
const schema = reactive<FormSchema[]>([
  {
    field: 'mgtOrgName',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'custNo',
    label: '用户编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户编号'
    }
  },
  {
    field: 'custName',
    label: '用户名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户名称'
    }
  },
  // {
  //   field: 'custClsName',
  //   label: '客户分类',
  //   component: 'Select',
  //   componentProps: {
  //     placeholder: '请选择客户分类',
  //     options: custClsOptions,
  //     multiple: true,
  //     collapseTags: true,
  //     collapseTagsTooltip: true,
  //     clearable: true
  //   }
  // },
  {
    field: 'ecCategName',
    label: '用电类别',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择用电类别',
      props: {
        checkStrictly: true,
        emitPath: false,
        multiple: true
      },
      options: ecCategOptions
    }
  },
  {
    field: 'instAddr',
    label: '用户地址',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户地址'
    }
  }
])

// 配置API请求
const config: DifyConfig = {
  apiKey: DIFY_API_KEY,
  apiBase: DIFY_API_V1_URL
}

// 使用useTable hook进行表格数据管理
const { tableRegister, tableMethods, tableState } = useTable({
  immediate: true, // 立即请求
  fetchDataApi: async () => {
    try {
      // 获取搜索表单数据
      const formData = await getFormData()

      // 模拟API请求 - 实际项目中应替换为真实API
      // 这里使用setTimeout模拟网络请求
      return new Promise((resolve) => {
        setTimeout(() => {
          // 这里是模拟数据，实际应该从后端API获取
          const mockData = [
            {
              mgtOrgCode: 'GD001',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL001',
              custNo: '1200032374605',
              custName: '张三',
              custCls: '03',
              custClsName: '低压居民',
              deregAttrCls: '0106',
              deregAttrClsName: '市场化普通直购客户',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN001',
              instCap: 75,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '01',
              instUsageClsName: '售电侧结算',
              eCalcModeCode: '01',
              eCalcModeCodeName: '实抄_装表计量',
              prcCode: 'PC001',
              readType: '01',
              readTypeName: '正向有功_总',
              thisMrQty: 2000,
              tSettleQty: 2000,
              tSettleExp: 1200,
              mrDevNo: 'MD001',
              devType: '010101',
              devTypeName: '电能表',
              becCalcMode: '01',
              becCalcModeName: '容量',
              pfStd: '04',
              pfStdName: '_0_9',
              pfEvalMode: '02',
              pfEvalModeName: '标准考核',
              lossNo: 'LN001',
              lossAlgFlag: '04',
              lossAlgFlagName: '按标准公式',
              voltage: '0107',
              adjDevNo: 'AD001',
              meterMode: '01',
              meterModeName: '低供低计',
              prcStType: '02',
              prcStTypeName: '单一制',
              // 新增处理状态和异常信息相关字段
              handler: '张工',
              handlerStatus: '待处理',
              abnorType: '档案异常',
              abnorCateg: '计费关系异常',
              abnorDtlInfo: '当月用电量较历史平均值偏高50%'
            },
            {
              mgtOrgCode: 'GD002',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL002',
              custNo: '1200032374605',
              custName: '李四',
              custCls: '02',
              custClsName: '低压非居民',
              deregAttrCls: '0102',
              deregAttrClsName: '市场化零售客户',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN002',
              instCap: 180,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '02',
              instUsageClsName: '台区供电考核',
              eCalcModeCode: '02',
              eCalcModeCodeName: '定比',
              prcCode: 'PC002',
              readType: '02',
              readTypeName: '正向有功_尖峰',
              thisMrQty: 3000,
              tSettleQty: 3000,
              tSettleExp: 2200,
              mrDevNo: 'MD002',
              devType: '010104',
              devTypeName: '采集装置',
              becCalcMode: '02',
              becCalcModeName: '实际最大需量',
              pfStd: '03',
              pfStdName: '_0_85',
              pfEvalMode: '03',
              pfEvalModeName: '只罚不奖',
              lossNo: 'LN002',
              lossAlgFlag: '02',
              lossAlgFlagName: '按定比',
              voltage: '0108',
              adjDevNo: 'AD002',
              meterMode: '02',
              meterModeName: '高供低计',
              prcStType: '01',
              prcStTypeName: '两部制',
              // 新增处理状态和异常信息相关字段
              handler: '王工',
              handlerStatus: '已处理',
              abnorType: '量费异常',
              abnorCateg: '电度电费异常',
              abnorDtlInfo: '当月电费较去年同期偏高35%'
            },
            {
              mgtOrgCode: 'GD003',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL003',
              custNo: '1200032374605',
              custName: '王五',
              custCls: '03',
              custClsName: '低压居民',
              deregAttrCls: '0106',
              deregAttrClsName: '市场化普通直购客户',
              ctrtCap: 150,
              runCap: 120,
              bilgUnitNo: 'AP003',
              ecCateg: 'PU001',
              ecCategName: '非居民照明',
              indCls: 'IT001',
              indClsName: '纺织业',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN003',
              instCap: 130,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '01',
              instUsageClsName: '售电侧结算',
              eCalcModeCode: '01',
              eCalcModeCodeName: '实抄_装表计量',
              prcCode: 'PC001',
              readType: '01',
              readTypeName: '正向有功_总',
              thisMrQty: 2500,
              tSettleQty: 2500,
              tSettleExp: 1500,
              mrDevNo: 'MD003',
              devType: '010101',
              devTypeName: '电能表',
              prcStType: '02',
              prcStTypeName: '单一制',
              becCalcMode: '01',
              becCalcModeName: '容量',
              pfStd: '04',
              pfStdName: '_0_9',
              pfEvalMode: '02',
              pfEvalModeName: '标准考核',
              lossNo: 'LN001',
              lossAlgFlag: '04',
              lossAlgFlagName: '按标准公式',
              voltage: '0107',
              adjDevNo: 'AD003',
              meterMode: '01',
              meterModeName: '低供低计'
            },
            {
              mgtOrgCode: 'GD004',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL004',
              custNo: '1200032374605',
              custName: '赵六',
              custCls: '01',
              custClsName: '高压',
              deregAttrCls: '0201',
              deregAttrClsName: '非市场化客户',
              ctrtCap: 500,
              runCap: 450,
              bilgUnitNo: 'AP004',
              ecCateg: 'PU003',
              ecCategName: '非居民照明',
              indCls: 'IT003',
              indClsName: '制造业',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN004',
              instCap: 480,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '03',
              instUsageClsName: '线路供电考核',
              eCalcModeCode: '03',
              eCalcModeCodeName: '定量',
              prcCode: 'PC003',
              readType: '03',
              readTypeName: '正向有功_峰',
              thisMrQty: 8000,
              tSettleQty: 8000,
              tSettleExp: 6000,
              mrDevNo: 'MD004',
              devType: '010102',
              devTypeName: '互感器',
              prcStType: '01',
              prcStTypeName: '两部制',
              becCalcMode: '04',
              becCalcModeName: '容需对比',
              pfStd: '02',
              pfStdName: '_0_8',
              pfEvalMode: '04',
              pfEvalModeName: '只奖不罚',
              lossNo: 'LN004',
              lossAlgFlag: '05',
              lossAlgFlagName: '按标准表',
              voltage: '0117',
              adjDevNo: 'AD004',
              meterMode: '03',
              meterModeName: '高供高计'
            },
            {
              mgtOrgCode: 'GD005',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL005',
              custNo: '1200032374605',
              custName: '钱七',
              custCls: '02',
              custClsName: '低压非居民',
              deregAttrCls: '0106',
              deregAttrClsName: '市场化普通直购客户',
              ctrtCap: 120,
              runCap: 100,
              bilgUnitNo: 'AP005',
              ecCateg: 'PU004',
              ecCategName: '非居民照明',
              indCls: 'IT004',
              indClsName: '农业',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN005',
              instCap: 110,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '04',
              instUsageClsName: '指标分析',
              eCalcModeCode: '01',
              eCalcModeCodeName: '实抄_装表计量',
              prcCode: 'PC004',
              readType: '01',
              readTypeName: '正向有功_总',
              thisMrQty: 1800,
              tSettleQty: 1800,
              tSettleExp: 1000,
              mrDevNo: 'MD005',
              devType: '010101',
              devTypeName: '电能表',
              prcStType: '02',
              prcStTypeName: '单一制',
              becCalcMode: '01',
              becCalcModeName: '容量',
              pfStd: '04',
              pfStdName: '_0_9',
              pfEvalMode: '02',
              pfEvalModeName: '标准考核',
              lossNo: 'LN005',
              lossAlgFlag: '04',
              lossAlgFlagName: '按标准公式',
              voltage: '0108',
              adjDevNo: 'AD005',
              meterMode: '02',
              meterModeName: '高供低计'
            },
            {
              mgtOrgCode: 'GD006',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL006',
              custNo: '1200032374605',
              custName: '孙八',
              custCls: '02',
              custClsName: '低压非居民',
              deregAttrCls: '0103',
              deregAttrClsName: '部分市场化零售客户',
              ctrtCap: 300,
              runCap: 280,
              bilgUnitNo: 'AP006',
              ecCateg: 'PU005',
              ecCategName: '非居民照明',
              indCls: 'IT005',
              indClsName: '商业服务',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN006',
              instCap: 290,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '05',
              instUsageClsName: '趸售供电关口',
              eCalcModeCode: '02',
              eCalcModeCodeName: '定比',
              prcCode: 'PC005',
              readType: '05',
              readTypeName: '正向有功_平',
              thisMrQty: 5000,
              tSettleQty: 5000,
              tSettleExp: 4000,
              mrDevNo: 'MD006',
              devType: '010201',
              devTypeName: '变压器',
              prcStType: '01',
              prcStTypeName: '两部制',
              becCalcMode: '03',
              becCalcModeName: '合约最大需量',
              pfStd: '03',
              pfStdName: '_0_85',
              pfEvalMode: '03',
              pfEvalModeName: '只罚不奖',
              lossNo: 'LN006',
              lossAlgFlag: '06',
              lossAlgFlagName: '按铜铁损公式',
              voltage: '0108',
              adjDevNo: 'AD006',
              meterMode: '02',
              meterModeName: '高供低计'
            },
            {
              mgtOrgCode: 'GD007',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL007',
              custNo: '1200032374605',
              custName: '周九',
              custCls: '03',
              custClsName: '低压居民',
              deregAttrCls: '0201',
              deregAttrClsName: '非市场化客户',
              ctrtCap: 80,
              runCap: 70,
              bilgUnitNo: 'AP007',
              ecCateg: 'PU001',
              ecCategName: '非居民照明',
              indCls: 'IT001',
              indClsName: '纺织业',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN007',
              instCap: 75,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '01',
              instUsageClsName: '售电侧结算',
              eCalcModeCode: '01',
              eCalcModeCodeName: '实抄_装表计量',
              prcCode: 'PC001',
              readType: '01',
              readTypeName: '正向有功_总',
              thisMrQty: 1500,
              tSettleQty: 1500,
              tSettleExp: 900,
              mrDevNo: 'MD007',
              devType: '010101',
              devTypeName: '电能表',
              prcStType: '02',
              prcStTypeName: '单一制',
              becCalcMode: '01',
              becCalcModeName: '容量',
              pfStd: '04',
              pfStdName: '_0_9',
              pfEvalMode: '02',
              pfEvalModeName: '标准考核',
              lossNo: 'LN007',
              lossAlgFlag: '04',
              lossAlgFlagName: '按标准公式',
              voltage: '0107',
              adjDevNo: 'AD007',
              meterMode: '01',
              meterModeName: '低供低计'
            },
            {
              mgtOrgCode: 'GD008',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL008',
              custNo: '9900000000023',
              custName: '吴十',
              custCls: '01',
              custClsName: '高压',
              deregAttrCls: '0106',
              deregAttrClsName: '市场化普通直购客户',
              ctrtCap: 800,
              runCap: 750,
              bilgUnitNo: 'AP008',
              ecCateg: 'PU003',
              ecCategName: '非居民照明',
              indCls: 'IT006',
              indClsName: '冶金行业',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN008',
              instCap: 780,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '03',
              instUsageClsName: '工业用电',
              eCalcModeCode: '03',
              eCalcModeCodeName: '定量',
              prcCode: 'PC006',
              readType: '03',
              readTypeName: '正向有功_峰',
              thisMrQty: 12000,
              tSettleQty: 12000,
              tSettleExp: 9000,
              mrDevNo: 'MD008',
              devType: '010102',
              devTypeName: '互感器',
              prcStType: '01',
              prcStTypeName: '两部制',
              becCalcMode: '04',
              becCalcModeName: '容需对比',
              pfStd: '02',
              pfStdName: '_0_8',
              pfEvalMode: '04',
              pfEvalModeName: '只奖不罚',
              lossNo: 'LN008',
              lossAlgFlag: '05',
              lossAlgFlagName: '按标准表',
              voltage: '0117',
              adjDevNo: 'AD008',
              meterMode: '03',
              meterModeName: '高供高计'
            },
            {
              mgtOrgCode: 'GD009',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL009',
              custNo: '9900000000023',
              custName: '郑十一',
              custCls: '02',
              custClsName: '低压非居民',
              deregAttrCls: '0102',
              deregAttrClsName: '市场化零售客户',
              ctrtCap: 250,
              runCap: 220,
              bilgUnitNo: 'AP009',
              ecCateg: 'PU006',
              ecCategName: '非居民照明',
              indCls: 'IT007',
              indClsName: '公共管理',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN009',
              instCap: 230,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '04',
              instUsageClsName: '公共设施用电',
              eCalcModeCode: '02',
              eCalcModeCodeName: '定比',
              prcCode: 'PC007',
              readType: '04',
              readTypeName: '正向有功_平',
              thisMrQty: 4200,
              tSettleQty: 4200,
              tSettleExp: 3500,
              mrDevNo: 'MD009',
              devType: '010201',
              devTypeName: '变压器',
              prcStType: '01',
              prcStTypeName: '两部制',
              becCalcMode: '03',
              becCalcModeName: '合约最大需量',
              pfStd: '03',
              pfStdName: '_0_85',
              pfEvalMode: '03',
              pfEvalModeName: '只罚不奖',
              lossNo: 'LN009',
              lossAlgFlag: '06',
              lossAlgFlagName: '按铜铁损公式',
              voltage: '0108',
              adjDevNo: 'AD009',
              meterMode: '02',
              meterModeName: '高供低计'
            },
            {
              mgtOrgCode: 'GD010',
              mgtOrgName: '河西大户管理区域',
              expYm: '2025-05',
              planNo: 'PL010',
              custNo: '9900000000023',
              custName: '王十二',
              custCls: '03',
              custClsName: '低压居民',
              deregAttrCls: '0106',
              deregAttrClsName: '市场化普通直购客户',
              ctrtCap: 100,
              runCap: 90,
              bilgUnitNo: 'AP010',
              ecCateg: 'PU004',
              ecCategName: '非居民照明',
              indCls: 'IT004',
              indClsName: '农业',
              instStat: '02',
              instStatName: '在用',
              instNo: 'IN010',
              instCap: 95,
              instAddr: '湖北省武汉市洪山区花山路XX号',
              instUsageCls: '04',
              instUsageClsName: '农业用电',
              eCalcModeCode: '01',
              eCalcModeCodeName: '实抄_装表计量',
              prcCode: 'PC004',
              readType: '01',
              readTypeName: '正向有功_总',
              thisMrQty: 1600,
              tSettleQty: 1600,
              tSettleExp: 950,
              mrDevNo: 'MD010',
              devType: '010101',
              devTypeName: '电能表',
              prcStType: '02',
              prcStTypeName: '单一制',
              becCalcMode: '01',
              becCalcModeName: '容量',
              pfStd: '04',
              pfStdName: '_0_9',
              pfEvalMode: '02',
              pfEvalModeName: '标准考核',
              lossNo: 'LN010',
              lossAlgFlag: '04',
              lossAlgFlagName: '按标准公式',
              voltage: '0108',
              adjDevNo: 'AD010',
              meterMode: '02',
              meterModeName: '高供低计'
            }
          ]

          // 根据查询条件过滤数据
          const filteredData = mockData.filter((item) => {
            if (formData.mgtOrgName && !item.mgtOrgName.includes(formData.mgtOrgName)) return false
            if (formData.custNo && !item.custNo.includes(formData.custNo)) return false
            if (formData.custName && !item.custName.includes(formData.custName)) return false
            if (formData.custClsName && item.custClsName !== formData.custClsName) return false
            if (formData.ecCategName && item.ecCategName !== formData.ecCategName) return false
            if (formData.instAddr && !item.instAddr.includes(formData.instAddr)) return false
            return true
          })

          // 返回查询结果
          resolve({
            list: filteredData,
            total: filteredData.length
          })
        }, 500)
      })
    } catch (error) {
      return Promise.reject(error)
    }
  }
})

// 从useTable中解构获取数据和状态
const { dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

// 表格列配置
const columns = reactive<TableColumn[]>([
  {
    field: '',
    type: 'selection', // 多选列
    width: 60,
    selection: true
  },
  {
    field: 'index',
    type: 'index', // 序号列
    label: '序号',
    width: 60,
    fixed: 'left'
  },
  {
    field: 'mgtOrgName',
    label: '管理单位',
    minWidth: 180
  },
  {
    field: 'custNo',
    label: '用户编号',
    minWidth: 120
  },
  {
    field: 'custName',
    label: '用户名称',
    minWidth: 100
  },
  {
    field: 'custClsName',
    label: '客户分类',
    minWidth: 110
  },
  {
    field: 'deregAttrClsName',
    label: '市场化属性分类',
    minWidth: 130
  },
  {
    field: 'ctrtCap',
    label: '合同容量',
    minWidth: 90
  },
  {
    field: 'runCap',
    label: '运行容量',
    minWidth: 90
  },
  {
    field: 'ecCategName',
    label: '用电类别',
    minWidth: 100
  },
  {
    field: 'action',
    label: '操作',
    width: 150,
    fixed: 'right',
    slots: {
      default: ({ row }) => {
        return [
          h(
            ElButton,
            {
              type: 'primary',
              link: true,
              onClick: () => viewDetails(row)
            },
            () => '查看详情'
          )
        ]
      }
    }
  }
])

// 详情弹窗相关参数
const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

// 查看详情
const viewDetails = (row) => {
  console.log('查看详情:', row)
  // ElMessage.success('查看详情功能待实现')
  currentDetail.value = {
    ...row
  }
  detailDialogVisible.value = true
}

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false
}

// 处理查询
const handleSearch = async () => {
  // 重置页码到第一页
  currentPage.value = 1
  refresh()
  ElMessage.success('查询成功')
}

// 处理重置
const handleReset = async () => {
  // 将重置页面和刷新数据交给Search组件完成
  currentPage.value = 1
  refresh()
}
// AI聊天相关
const chatSidebarRef = ref<ChatSidebarInstance | null>(null)
const aiInputs = ref({})

// 处理AI会话完成
const handleAiFinish = (result: any) => {
  console.log('AI会话结束:', result)
  if (result.extractedJson) {
    ElMessage.success('已提取数据，可用于后续处理')
  }
}
const { setProps } = tableMethods
// 在组件挂载后注册Search组件
onMounted(() => {
  // 设置固定表格高度 437.8
  setProps({
    height: 438
  })
  // 注册搜索组件
  if (searchRef.value) {
    searchRegister(searchRef.value)

    // 统一设置所有表单项的大小和宽度
    schema.forEach((item) => {
      setSchema([
        {
          field: item.field,
          path: 'componentProps.size',
          value: 'default'
        },
        {
          field: item.field,
          path: 'componentProps.style',
          value: { width: '300px' }
        }
      ])
    })
  }
})

// 处理ChatSidebarPanel的before-open事件
const handleBeforeOpen = () => {
  // 检查是否选中了至少一条数据
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条需识别的数据！')
    // 阻止打开聊天面板
    return false
  }
  chatSidebarRef.value?.openDrawer()

  // 设置AI输入数据
  aiInputs.value = {
    table_data: JSON.stringify(selectedRows.value)
  }

  return true
}

// 表格样式，奇行背景色#f6f6f6偶行背景色#ffffff
const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}

const submissionData = reactive<any>({})

// const handleSubmit = async () => {
//   try {
//     const res = (await updateArchiveVerification(submissionData)) as IResponse<any>
//     if (res && res.code === 200) {
//       ElMessage.success('提交成功')
//       // ... existing code ...
//     }
//   } catch (error) {
//     // ... existing code ...
//   }
// }
</script>

<template>
  <!-- 搜索表单 - 使用项目封装的Search组件 -->
  <Search
    ref="searchRef"
    :schema="schema"
    label-width="100px"
    :layout="'bottom'"
    :button-position="'right'"
    @search="handleSearch"
    @reset="handleReset"
  />
  <div>总计：{{ total }}条数据</div>

  <!-- 表格 - 使用项目封装的Table组件 -->
  <Table
    v-model:pageSize="pageSize"
    v-model:currentPage="currentPage"
    :loading="tableState.loading.value"
    :data="dataList"
    :columns="columns"
    row-key="planNo"
    height="450"
    :fit="true"
    :pagination="{
      total: total,
      pageSize: pageSize,
      currentPage: currentPage,
      pageSizes: [10, 20, 30, 40, 50],
      background: true
    }"
    style="
      --el-table-border-color: #cdd7d5;
      --el-table-text-color: #171717;
      --el-table-header-text-color: #585858;
    "
    :header-cell-style="{
      background: '#e5f5f3', // 背景色
      color: '#585858' // 文字颜色
    }"
    :row-style="tableRowStyle"
    @register="tableRegister"
    @selection-change="handleSelectionChange"
  />

  <!-- 智能聊天悬浮按钮 -->
  <!-- <div class="floating-chat-button">
      <div class="ai-chat-button" @click="openChatDialog">
        <div class="robot-icon">
          <img src="@/assets/images/robot-icon.jpg" alt="智能体图标" />
        </div>
        <div class="text-content">
          <span class="sub-text">异常识别</span>
          <span class="sub-text">智能体</span>
        </div>
      </div>
    </div> -->

  <!-- 智能聊天对话框
    <ElDialog
      v-model="chatDialogVisible"
      title="电费异常智能分析"
      width="80%"
      destroy-on-close
      append-to-body
      class="chat-dialog"
    >
      <div style="height: 600px">
        <IntelligentChat
          apiKey="app-XBcoWGd3UPMrLaJMljSdMGdc"
          apiBase="http://192.168.1.3/v1"
          :inputs="aiInputs"
          @message-end="handleAiFinish"
          placeholder="请输入您想了解的电费异常问题..."
        />
      </div>
    </ElDialog> -->

  <!-- 侧边栏聊天组件 -->
  <ChatSidebarPanel
    ref="chatSidebarRef"
    :api-key="DIFY_API_KEY_changjing1"
    :api-base="DIFY_API_V1_URL"
    :inputs="aiInputs"
    title="用户档案核查助手"
    placeholder="请输入您想了解的问题..."
    welcome-message="您好！我是用户档案核查助手。我可以帮您分析用户档案问题，提供解决方案。请问有什么需要帮助的吗？"
    @message-end="handleAiFinish"
    @before-open="handleBeforeOpen"
    :show-float-button="true"
  />

  <!-- 详情弹窗 -->
  <ElDialog
    v-model="detailDialogVisible"
    title="详情"
    width="70%"
    :before-close="closeDetailDialog"
    destroy-on-close
    class="detail-dialog"
    style=""
  >
    <div class="detail-container">
      <div class="detail-section">
        <div class="detail-title">基础档案信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">管理单位：</div>
            <div class="detail-value">{{ currentDetail?.mgtOrgName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用户编号：</div>
            <div class="detail-value">{{ currentDetail?.custNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用户名称：</div>
            <div class="detail-value">{{ currentDetail?.custName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">客户分类：</div>
            <div class="detail-value">{{ currentDetail?.custClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">市场化属性分类：</div>
            <div class="detail-value">{{ currentDetail?.deregAttrClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">合同容量：</div>
            <div class="detail-value">{{ currentDetail?.ctrtCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">运行容量：</div>
            <div class="detail-value">{{ currentDetail?.runCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用电类别：</div>
            <div class="detail-value">{{ currentDetail?.ecCategName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">行业分类：</div>
            <div class="detail-value">{{ currentDetail?.indClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">价格码：</div>
            <div class="detail-value">{{ currentDetail?.prcCode }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">定价策略类型：</div>
            <div class="detail-value">{{ currentDetail?.prcStTypeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">基本电费计算方式：</div>
            <div class="detail-value">{{ currentDetail?.becCalcModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">功率因数考核标准：</div>
            <div class="detail-value">{{ currentDetail?.pfStdName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">功率因数考核方式：</div>
            <div class="detail-value">{{ currentDetail?.pfEvalModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">电压等级：</div>
            <div class="detail-value">{{ currentDetail?.voltage }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">计量点信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">安装点状态：</div>
            <div class="detail-value">{{ currentDetail?.instStatName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点编号：</div>
            <div class="detail-value">{{ currentDetail?.instNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点容量：</div>
            <div class="detail-value">{{ currentDetail?.instCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">计量方式：</div>
            <div class="detail-value">{{ currentDetail?.meterModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点用途分类：</div>
            <div class="detail-value">{{ currentDetail?.instUsageClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">能源计算方式：</div>
            <div class="detail-value">{{ currentDetail?.eCalcModeCodeName }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section-end">
        <div class="detail-title">设备信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">表计设备编号：</div>
            <div class="detail-value">{{ currentDetail?.mrDevNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">表计类型：</div>
            <div class="detail-value">{{ currentDetail?.devTypeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">损耗编号：</div>
            <div class="detail-value">{{ currentDetail?.lossNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">变损计算方式：</div>
            <div class="detail-value">{{ currentDetail?.lossAlgFlagName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">调压设备编码：</div>
            <div class="detail-value">{{ currentDetail?.adjDevNo }}</div>
          </div>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<style lang="scss" scoped>
.operation-button {
  margin-left: 8px;
}

.mr-5px {
  margin-right: 5px;
}

/* 导入对话框样式 */
.import-dialog-content {
  padding: 20px 0;

  .upload-area {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;

    .upload-dragger {
      width: 100%;
    }

    .upload-icon {
      font-size: 48px;
      color: #409eff;
      margin-bottom: 10px;
    }

    .upload-text {
      text-align: center;
      color: #606266;

      .upload-hint {
        font-size: 12px;
        color: #909399;
        margin-top: 5px;
      }
    }
  }

  .template-download {
    text-align: center;
    margin-top: 20px;
  }
}

// /* 悬浮聊天按钮样式 */
// .floating-chat-button {
//   position: fixed;
//   right: 20px;
//   bottom: 160px;
//   z-index: 999;

//   .ai-chat-button {
//     display: flex;
//     flex-direction: column;
//     align-items: center;
//     background-color: #ffffff;
//     border-radius: 16px;
//     box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.12);
//     padding: 12px;
//     cursor: pointer;
//     width: 90px;
//     height: 120px;
//     transition: all 0.3s;

//     &:hover {
//       box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.15);
//       transform: translateY(-3px);
//     }

//     .robot-icon {
//       width: 60px;
//       height: 60px;
//       margin-bottom: 8px;

//       img {
//         width: 100%;
//         height: 100%;
//       }
//     }

//     .text-content {
//       display: flex;
//       flex-direction: column;
//       align-items: center;
//       color: #4e7ae7;

//       .sub-text {
//         font-size: 14px;
//         line-height: 1.2;
//       }
//     }
//   }
// }

// .chat-dialog {
//   :deep(.el-dialog__body) {
//     padding: 0;
//   }
// }

/* 详情弹窗样式 */
.detail-container {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  background-color: #f2f2f2;
  padding: 26px 6px 26px 26px;
}

.detail-section {
  padding: 6px;
  border-bottom: 1px solid #999;
}

.detail-section-end {
  padding: 6px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 4px;
  margin-bottom: 6px;
}

.detail-info {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 0 0 0 70px;
}

.detail-item {
  width: 33.333%;
  min-height: 30px;
  display: flex;
  padding: 10px;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  // min-width: 130px;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}
</style>
